package com.centaline.androidsalesblog.activities.mine;

import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.api.usercenter.UpdateUserInfoApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.events.UserOperate;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.UserRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.interfaces.IResponseListener;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 修改昵称
 * <p>
 * Created by fusl1 on 2015/12/28.
 * Modify by Lihq on 2016/01/17
 */
public class SettingsNickNameActivity extends BaseActivity {

    private EditText et_nickname;//提交修改
    private Button btn_confirm;

    private UpdateUserInfoApi updateUserInfoApi;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_settings_nickname;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_settings_nickname);
        et_nickname = (EditText) findViewById(R.id.et_nickname);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
    }

    @Override
    protected void initViews() {
        Observable<CharSequence> nickNameObservable = RxTextView.textChanges(et_nickname).skip(1);
        nickNameObservable.compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<CharSequence>() {
                    @Override
                    public void call(CharSequence charSequence) {
                        btn_confirm.setEnabled(charSequence.length() > 0);
                    }
                });
        RxView.clicks(btn_confirm)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        updateUserInfo();
                    }
                });

        updateUserInfoApi = new UpdateUserInfoApi(SettingsNickNameActivity.class, UserRo.class, new IResponseListener<UserRo>() {
            @Override
            public void onResponse(UserRo userRo) {
                UserDo userDo = userRo.getUserDo();
                if (userRo.getResultNo() == 0 &&
                        userDo != null) {
                    userSave(userDo);
                } else {
                    cancelLoadingDialog();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkUnable();
            }
        });
        userInfo();
    }

    /**
     * 更新用户信息
     */
    private void updateUserInfo() {
        showLoadingDialog();
        updateUserInfoApi.setNickName(et_nickname.getText().toString());
        updateUserInfoApi.startRequest();
    }

    /**
     * 保存用户信息
     */
    private void userSave(final UserDo userDo) {
        AppConstant.setUserLogin(this, userDo);
        RxDataBase.saveUser(userDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        EventBus.getDefault().post(new UserOperate(1));
                        cancelLoadingDialog();
                        toast("更新成功");
                        setResult(RESULT_OK, new Intent().putExtra(ExtraConstant.NICK_NAME, userDo.getNickName()));
                        finish();
                    }
                });
    }

    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        et_nickname.setText(userDo.getNickName());
                        et_nickname.setSelection(et_nickname.getText().length());
                        updateUserInfoApi.setPhone(userDo.getPhone());
                        updateUserInfoApi.setIsPushSystemMsg(String.valueOf(userDo.isPushSystemMsg()));
                        updateUserInfoApi.setIsPushChat(String.valueOf(userDo.isPushChat()));
                        updateUserInfoApi.setIsPushPost(String.valueOf(userDo.isPushPost()));
                        updateUserInfoApi.setIsPushEstate(String.valueOf(userDo.isPushEstate()));
                    }
                });
    }
}
